package cn.breeze.basic.interceptor;

import cn.breeze.basic.annotation.PreAuthorize;
import cn.breeze.basic.jwt.*;
import cn.breeze.org.mapper.EmployeeMapper;
import cn.breeze.system.mapper.PermissionMapper;
import cn.breeze.user.domain.Logininfo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("jwt/pethome_auth_rsa.pub")
    private String jwtRsaPub;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取前端传过来的token
        String token = request.getHeader("token");
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 判断是否有token
        if (token != null){
            // 2 解析token里面内容
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPub).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            // 如果查到了
            if (payload != null){
                UserInfo userInfo = payload.getUserInfo();
                Logininfo logininfo = userInfo.getLogininfo();
                // 判断当前用户是前台还是后台用户
                if (logininfo.getType() == 0){
                    // 判断当前请求URL是否有加注解
                    HandlerMethod handlerMethod = (HandlerMethod)handler;
                    PreAuthorize methodAnnotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (methodAnnotation != null){
                        // 判断当前用户是否有当前访问的URL权限
                        String sn = methodAnnotation.sn();
                        if (!userInfo.getPermissions().contains(sn)){
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                // 重置过期时间为30分钟
                /*redisTemplate.opsForValue().set(
                        token,
                        logininfo,
                        30,
                        TimeUnit.MINUTES
                );*/
                // 放行
                return true;
            }
        }
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}
